<?php
declare(strict_types=1);

namespace app\model;

use think\Model;

class Merchant extends Model
{
    // 设置表名
    protected $name = 'merchant';
    
    // 设置字段信息
    protected $schema = [
        'id'          => 'int',
        'status'      => 'int',
        'update_time'  => 'datetime',
        'create_time'    => 'datetime',

    ];
    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $timeFormat = 'Y-m-d H:i:s';
    
    // 允许修改的字段
    protected $allowField = ['status', 'remark', 'update_time'];

    /**
     * 获取分销配置
     */
    public function getDistributionConfig(): array
    {
        return [
            'enabled' => (bool)$this->distribution_enabled,
            'level1_rate' => floatval($this->level1_rate),
            'level2_rate' => floatval($this->level2_rate)
        ];
    }

    /**
     * 计算分销佣金
     * @param float $merchantCommission 商家佣金
     * @param int $userId 用户ID
     * @return array [level1_commission, level2_commission, level1_user_id, level2_user_id]
     */
    public function calculateDistributionCommission(float $merchantCommission, int $userId): array
    {
        if (!$this->distribution_enabled) {
            return [0, 0, 0, 0];
        }

        // 获取用户的推荐人
        $user = User::find($userId);
        if (!$user || !$user->parent_id) {
            return [0, 0, 0, 0];
        }

        // 计算一级佣金
        $level1Commission = round($merchantCommission * $this->level1_rate, 2);
        $level1UserId = $user->parent_id;

        // 获取二级推荐人
        $level1User = User::find($level1UserId);
        $level2Commission = 0;
        $level2UserId = 0;
        
        if ($level1User && $level1User->parent_id) {
            $level2Commission = round($merchantCommission * $this->level2_rate, 2);
            $level2UserId = $level1User->parent_id;
        }

        return [$level1Commission, $level2Commission, $level1UserId, $level2UserId];
    }

    /**
     * 关联商家应用表
     */
    public function applications()
    {
        return $this->hasMany(MerchantApplication::class, 'merchant_id', 'id');
    }
} 